/**
 * Custom Jest serializer for snapshots of the talons and hooks APIs.
 * We want to let developers know that whenever they add to or modify the file
 * structure in the `lib/talons` and `lib/hooks` directories, they've changed
 * the APIs for the talons and/or hooks targets. We'll do that with a special
 * serializer with readable output.
 * @ignore
 */
const path = require('path');
const HookInterceptorSet = require('./HookInterceptorSet');
const TargetableHook = require('./TargetableHook');

module.exports = {
    serialize(interceptorSet, config, indentation) {
        const baseDir = path.basename(interceptorSet._hookDir);

        const lines = [];
        const walkApi = (node, dotPath) => {
            if (node instanceof TargetableHook) {
                lines.push(
                    `${
                        config.indent
                    }${baseDir}${dotPath}.wrapWith() wraps export "${
                        node._exportName
                    }" from "${path.relative(
                        interceptorSet._hookDir,
                        require.resolve(node._talonModule.file)
                    )}"`
                );
            } else {
                for (const [key, value] of Object.entries(node)) {
                    if (!key.startsWith('_') && typeof value === 'object') {
                        walkApi(value, dotPath + '.' + key);
                    }
                }
            }
        };

        walkApi(interceptorSet, '');
        return (
            `HookInterceptorSet API (autogenerated from "@magento/peregrine/lib/${baseDir}"):\n${indentation}` +
            lines.sort().join(`\n${indentation}`)
        );
    },
    test: val => val instanceof HookInterceptorSet
};
